package com.ljx.blog.article.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljx.blog.article.domain.entity.Theme;
import com.ljx.blog.article.domain.vo.req.ThemeSubmitReq;
import com.ljx.blog.article.domain.vo.resp.ThemeResp;
import com.ljx.blog.article.mapper.ThemeMapper;
import com.ljx.blog.article.service.ThemeService;
import com.ljx.blog.common.enums.CommonStatusTypeEnum;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Author: LiJunXi
 * @Description:
 * @Date: 2024-10-12  22:07
 */
@Service
public class ThemeServiceImpl extends ServiceImpl<ThemeMapper, Theme> implements ThemeService {

    @Autowired
    private ThemeMapper themeMapper;


    @Override
    public ThemeResp getInfo(Long ThemeId) {
        Theme theme = themeMapper.selectById(ThemeId);
        return BeanUtil.copyProperties(theme, ThemeResp.class);
    }

    @Override
    @Transactional
    public ThemeResp submit(ThemeSubmitReq req) {
        Theme theme;
        if (Objects.isNull(req.getId())){
            theme = BeanUtil.copyProperties(req, Theme.class);
            themeMapper.insert(theme);
        } else {
            theme = themeMapper.selectById(req.getId());
            BeanUtils.copyProperties(req, Theme.class);
            themeMapper.updateById(theme);
        }
        return getInfo(req.getId());
    }

    @Override
    public List<ThemeResp> init() {
        List<Theme> themes = themeMapper.selectList(new LambdaQueryWrapper<Theme>()
                .eq(Theme::getStatus, CommonStatusTypeEnum.NORMAL.getKey()));
        return BeanUtil.copyToList(themes, ThemeResp.class);
    }

    @Override
    public List<ThemeResp> batchSubmit(List<ThemeSubmitReq> req) {
        if (CollUtil.isEmpty(req)){
            return new ArrayList<>();
        }

        List<Long> themesIds = req.stream().map(ThemeSubmitReq::getId).collect(Collectors.toList());
        Map<Long, ThemeSubmitReq> themeMap = req.stream().collect(Collectors.toMap(ThemeSubmitReq::getId, Function.identity()));
        List<Theme> themes = themeMapper.selectBatchIds(themesIds).stream().map(item -> {
            ThemeSubmitReq themeSubmitReq = themeMap.get(item.getId());
            item.setDefaultValue(themeSubmitReq.getDefaultValue());
            return item;
        }).collect(Collectors.toList());
        updateBatchById(themes);
        return BeanUtil.copyToList(themes, ThemeResp.class);
    }
}
